const split = (str, char) => {
    const [prev, ...next] = str.split(char);
    return [prev, next.join(char)];
};

// 路由匹配
function match(url = '', obj = {}) {
    const urlItems = url.trim().split('/');

    let params = {};
    let router = '';
    const matched = Object.keys(obj).some(route => {
        const routeItems = route.trim().split('/');
        router = '';

        // 全局匹配的级别最低，一般用来处理404
        if (route === '*') return false;

        // 长度相等
        if (routeItems.length === urlItems.length) {
            params = {}; // 获取参数
            router = route; // 匹配到的路由地址

            return routeItems.every((i, index) => {
                let urlItemsItem = urlItems[index];
                // 参数匹配
                if (/^[^:@]*:/.test(i)) {
                    const [prev, rules] = split(i, ':');
                    // 对 /:id的支持
                    if (urlItemsItem.startsWith(prev)) {
                        urlItemsItem = urlItemsItem.slice(prev.length);
                        // 对 /:id的支持
                        const [key, reg] = split(rules, '@');
                        params[key] = urlItemsItem;

                        // 对正则表达式的支持 /:name@aa.+
                        if (reg) {
                            return new RegExp(`^${reg}$`).test(urlItemsItem);
                        }
                        return true;
                    }
                }

                // * 匹配所有
                if (i === '*') {
                    return true;
                }

                // 常规性匹配 Abc*
                if (i.includes('*')) {
                    const reg = i.replace('*', '.*');
                    return new RegExp(`^${reg}$`).test(urlItemsItem);
                }

                // 纯文匹配
                return i === urlItemsItem;
            });
        }

        return false;
    });

    if (matched) {
        return {
            params,
            url,
            router,
            value: obj[router]
        };
    }
    return null;
}
exports.matchByPathname = function matchByPathname(url = '', obj = {}) {
    const pathname = url.split('?')[0];
    return match(pathname, obj);
};
